//
//  FMKeychainTool.m
//  flutter_device_info_plugin
//

#import "FMKeychainTool.h"

@implementation FMKeychainTool

+ (BOOL)saveData:(NSString *)data {
    NSData *datas = [data dataUsingEncoding:NSUTF8StringEncoding];
    
    NSDictionary *param = @{
        (__bridge id)kSecClass: (__bridge id)kSecClassGenericPassword,
        (__bridge id)kSecAttrService: @"com.furahaMkopo.service",
        (__bridge id)kSecValueData: datas
    };

    SecItemDelete((__bridge CFDictionaryRef)param);
    
    OSStatus st = SecItemAdd((__bridge CFDictionaryRef)param, NULL);
    
    return (st == errSecSuccess);
}

+ (NSString *)getData {
    NSDictionary *param = @{
        (__bridge id)kSecClass: (__bridge id)kSecClassGenericPassword,
        (__bridge id)kSecAttrService: @"com.furahaMkopo.service",
        (__bridge id)kSecReturnData: @YES,
        (__bridge id)kSecMatchLimit: (__bridge id)kSecMatchLimitOne
    };
    
    CFTypeRef result = NULL;
    OSStatus st = SecItemCopyMatching((__bridge CFDictionaryRef)param, &result);
    
    if (st == errSecSuccess) {
        NSData *data = (__bridge_transfer NSData *)result;
        return [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    }
    
    return nil;
}

@end
